package org.dromara.dp.controller;

import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.dp.vo.BusinessIndicatorVo;
import org.dromara.dp.vo.RiskIndexVo;
import org.dromara.dp.vo.RiskSubItemVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RequiredArgsConstructor
@RestController
@RequestMapping("/dp")
public class GisRiskIndexController {

    /**
     * 大屏风险指数统计
     */
    @GetMapping("/gis/risk-index/statistics")
    public R<Map<String, Object>> statistics() {
        Map<String, Object> result = new HashMap<>();
        // 双重预防
        RiskIndexVo doublePrevention = new RiskIndexVo();
        doublePrevention.setWeightedScore(BigDecimal.valueOf(18.2));
        doublePrevention.setScore(BigDecimal.valueOf(91));
        doublePrevention.setRiskSubItemVos(Arrays.asList(
            createSubItem("隐患排查", (byte) 0, BigDecimal.valueOf(4), "存在两个超期未整改的隐患"),
            createSubItem("双重预防运行效果", (byte) 0, BigDecimal.valueOf(5), "双重预防机制效果评估为中")
        ));
        result.put("doublePrevention", doublePrevention);

        // 工艺报警
        RiskIndexVo processAlarm = new RiskIndexVo();
        processAlarm.setWeightedScore(BigDecimal.valueOf(14.7));
        processAlarm.setScore(BigDecimal.valueOf(98));
        processAlarm.setRiskSubItemVos(Arrays.asList(
            createSubItem("操作平稳率", (byte) 0, BigDecimal.valueOf(2), "操作平稳率为89%"),
            createSubItem("工艺报警", (byte) 0, BigDecimal.valueOf(0), null)
        ));
        result.put("processAlarm", processAlarm);

        // 设备可靠性
        RiskIndexVo deviceRun = new RiskIndexVo();
        deviceRun.setWeightedScore(BigDecimal.valueOf(14.4));
        deviceRun.setScore(BigDecimal.valueOf(96));
        deviceRun.setRiskSubItemVos(Arrays.asList(
            createSubItem("重点设备运行", (byte) 0, BigDecimal.valueOf(0), null),
            createSubItem("设备检维修", (byte) 0, BigDecimal.valueOf(4), "设备检维修计划完成率为88%")
        ));
        result.put("deviceRun", deviceRun);

        // 控制回路
        RiskIndexVo controlCircuit = new RiskIndexVo();
        controlCircuit.setWeightedScore(BigDecimal.valueOf(0));
        controlCircuit.setScore(BigDecimal.valueOf(0));
        controlCircuit.setRiskSubItemVos(List.of(
            createSubItem("有效自控率", (byte) 1, BigDecimal.valueOf(100), "出现否决项，有效自控率为49%")
        ));
        result.put("controlCircuit", controlCircuit);

        // SIS联锁旁路
        RiskIndexVo sisSide = new RiskIndexVo();
        sisSide.setWeightedScore(BigDecimal.valueOf(12.75));
        sisSide.setScore(BigDecimal.valueOf(85));
        sisSide.setRiskSubItemVos(List.of(
            createSubItem("SIS连锁旁路", (byte) 0, BigDecimal.valueOf(15), "有三处SIS连锁旁路")
        ));
        result.put("sisSide", sisSide);

        // GDS报警
        RiskIndexVo gdsAlarm = new RiskIndexVo();
        gdsAlarm.setWeightedScore(BigDecimal.valueOf(4.25));
        gdsAlarm.setScore(BigDecimal.valueOf(85));
        gdsAlarm.setRiskSubItemVos(List.of(
            createSubItem("可燃气体报警", (byte) 0, BigDecimal.valueOf(15), "有三次有毒可燃气体报警器报警")
        ));
        result.put("gdsAlarm", gdsAlarm);

        // 特殊作业
        RiskIndexVo specialWork = new RiskIndexVo();
        specialWork.setWeightedScore(BigDecimal.valueOf(14.1));
        specialWork.setScore(BigDecimal.valueOf(94));
        specialWork.setRiskSubItemVos(Arrays.asList(
            createSubItem("动火作业", (byte) 0, BigDecimal.valueOf(6), "有三处二级动火"),
            createSubItem("受限空间作业", (byte) 0, BigDecimal.valueOf(0), null),
            createSubItem("高处作业", (byte) 0, BigDecimal.valueOf(0), null),
            createSubItem("吊装作业", (byte) 0, BigDecimal.valueOf(0), null)
        ));
        result.put("specialWork", specialWork);

        // 人员聚集
        RiskIndexVo personAggregation = new RiskIndexVo();
        personAggregation.setWeightedScore(BigDecimal.valueOf(9.5));
        personAggregation.setScore(BigDecimal.valueOf(95));
        personAggregation.setRiskSubItemVos(List.of(
            createSubItem("人员聚集", (byte) 0, BigDecimal.valueOf(5), "出现橙色报警")
        ));
        result.put("personAggregation", personAggregation);
        // 指数总分
        result.put("indexScore", BigDecimal.valueOf(87.9));
        // 总分
        result.put("totalScore", BigDecimal.valueOf(644));
        return R.ok(result);
    }

    /**
     * 总体安全指数统计
     */
    @GetMapping("/gis/overall-safety-index/statistics")
    public R<Map<String, Object>> statisticsOverallSafetyIndex() {
        Map<String, Object> result = new HashMap<>();

        // 仪表盘数据 - 近7天和近30天平均指数
        result.put("last7DaysAverageIndex", 75);  // 近7天平均指数
        result.put("last30DaysAverageIndex", 80); // 近30天平均指数

        // 近7天数据
        Map<String, Object> last7DaysData = new HashMap<>();
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        // 近7天日期
        List<String> last7DaysDates = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            last7DaysDates.add(date.format(formatter));
        }
        last7DaysData.put("dates", last7DaysDates);

        // 近7天线数据（紫色）
        int[] last7DaysPurpleLine = {75, 75, 75, 75, 75, 75, 75};
        last7DaysData.put("purple", last7DaysPurpleLine);

        // 近7天线数据（蓝色）
        int[] last7DaysBlueLine = {71, 70, 72, 75, 78, 79, 80};
        last7DaysData.put("blue", last7DaysBlueLine);

        result.put("last7Days", last7DaysData);

        // 近30天数据
        Map<String, Object> last30DaysData = new HashMap<>();

        // 近30天日期
        List<String> last30DaysDates = new ArrayList<>();
        for (int i = 29; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            last30DaysDates.add(date.format(formatter));
        }
        last30DaysData.put("dates", last30DaysDates);

        // 近30天线数据（紫色）
        int[] last30DaysPurpleLine = new int[30];
        Arrays.fill(last30DaysPurpleLine, 80);
        last30DaysData.put("purple", last30DaysPurpleLine);

        // 近30天线数据（蓝色）
        int[] last30DaysBlueLine = new int[30];
        int[] blueIndex = {85, 80, 80, 75};
        for (int i = 0; i < 30; i++) {
            int weekIndex = i / 7;
            if (weekIndex == blueIndex.length) {
                weekIndex = blueIndex.length - 1;
            }
            last30DaysBlueLine[i] = blueIndex[weekIndex];
        }
        last30DaysData.put("blue", last30DaysBlueLine);
        result.put("last30Days", last30DaysData);
        return R.ok(result);
    }

    /**
     * 业务指标统计
     */
    @GetMapping("/gis/business-indicators/statistics")
    public R<Map<String, Object>> statisticsBusinessIndicators() {
        Map<String, Object> result = new HashMap<>();
        // 事故事件
        result.put("accidentStats", new BusinessIndicatorVo.AccidentStats(0, 0, 0));

        // 双预防
        Map<String, BusinessIndicatorVo.DoublePreventionStats> doublePrevention = new HashMap<>();
        doublePrevention.put("last7Days", new BusinessIndicatorVo.DoublePreventionStats(2, 0, 0));
        doublePrevention.put("last30Days", new BusinessIndicatorVo.DoublePreventionStats(6, 0, 0));
        doublePrevention.put("currentYear", new BusinessIndicatorVo.DoublePreventionStats(45, 0, 0));
        result.put("doublePrevention", doublePrevention);

        // 控制回路
        Map<String, BusinessIndicatorVo.ControlLoop> controlLoop = new HashMap<>();
        controlLoop.put("last7Days", new BusinessIndicatorVo.ControlLoop(0.49));
        controlLoop.put("last30Days", new BusinessIndicatorVo.ControlLoop(0.65));
        controlLoop.put("currentYear", new BusinessIndicatorVo.ControlLoop(0.72));
        result.put("controlLoop", controlLoop);

        // 设备可靠性
        Map<String, BusinessIndicatorVo.DeviceRun> deviceRun = new HashMap<>();
        deviceRun.put("last7Days", new BusinessIndicatorVo.DeviceRun(0.88, 3, 0));
        deviceRun.put("last30Days", new BusinessIndicatorVo.DeviceRun(0.91, 13, 0));
        deviceRun.put("currentYear", new BusinessIndicatorVo.DeviceRun(0.89, 103, 0));
        result.put("deviceRun", deviceRun);

        // 工艺报警
        Map<String, BusinessIndicatorVo.ProcessAlarm> processAlarm = new HashMap<>();
        processAlarm.put("last7Days", new BusinessIndicatorVo.ProcessAlarm(0.89, 13, 0));
        processAlarm.put("last30Days", new BusinessIndicatorVo.ProcessAlarm(0.90, 56, 3));
        processAlarm.put("currentYear", new BusinessIndicatorVo.ProcessAlarm(0.88, 275, 3));
        result.put("processAlarm", processAlarm);

        // SIS连锁
        Map<String, BusinessIndicatorVo.SisSide> sisSide = new HashMap<>();
        sisSide.put("last7Days", new BusinessIndicatorVo.SisSide(3));
        sisSide.put("last30Days", new BusinessIndicatorVo.SisSide(9));
        sisSide.put("currentYear", new BusinessIndicatorVo.SisSide(15));
        result.put("sisSide", sisSide);

        // GDS报警
        Map<String, BusinessIndicatorVo.GDSAlarm> gdsAlarm = new HashMap<>();
        gdsAlarm.put("last7Days", new BusinessIndicatorVo.GDSAlarm(3, 3, 0));
        gdsAlarm.put("last30Days", new BusinessIndicatorVo.GDSAlarm(9, 9, 0));
        gdsAlarm.put("currentYear", new BusinessIndicatorVo.GDSAlarm(45, 42, 3));
        result.put("gdsAlarm", gdsAlarm);

        // 特殊作业
        Map<String, BusinessIndicatorVo.SpecialWorkStats> specialWork = new HashMap<>();
        specialWork.put("last7Days", new BusinessIndicatorVo.SpecialWorkStats(3, 3, 0, 0, 0));
        specialWork.put("last30Days", new BusinessIndicatorVo.SpecialWorkStats(12, 6, 2, 4, 0));
        specialWork.put("currentYear", new BusinessIndicatorVo.SpecialWorkStats(30, 14, 4, 12, 0));
        result.put("specialWork", specialWork);

        // 人员聚集
        Map<String, BusinessIndicatorVo.PersonAggregation> personAggregation = new HashMap<>();
        personAggregation.put("last7Days", new BusinessIndicatorVo.PersonAggregation(0, 1, 0));
        personAggregation.put("last30Days", new BusinessIndicatorVo.PersonAggregation(0, 2, 0));
        personAggregation.put("currentYear", new BusinessIndicatorVo.PersonAggregation(0, 3, 0));
        result.put("personAggregation", personAggregation);
        return R.ok(result);
    }

    /**
     * 安全指数折线图
     */
    @GetMapping("/gis/risk-indicator-line")
    public R<Map<String, Object>> getRiskIndicatorLine() {
        Map<String, Object> result = new HashMap<>();
        // 动态生成最近24小时的时间点（从当天0点到当前时间）
        List<String> timePoints = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:00");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取当天0点
        LocalDateTime startOfDay = now.toLocalDate().atStartOfDay();
        // 生成从0点到当前小时的时间点
        for (int i = 0; i <= now.getHour(); i++) {
            LocalDateTime time = startOfDay.plusHours(i);
            timePoints.add(time.format(formatter));
        }
        result.put("timePoints", timePoints);
        int currentHour = now.getHour();
        // 双预防
        BigDecimal[] doublePreventionData = {
            BigDecimal.valueOf(18.0), BigDecimal.valueOf(17.9), BigDecimal.valueOf(18.1),
            BigDecimal.valueOf(18.2), BigDecimal.valueOf(18.3), BigDecimal.valueOf(18.1),
            BigDecimal.valueOf(18.2), BigDecimal.valueOf(18.2), BigDecimal.valueOf(18.0),
            BigDecimal.valueOf(17.9), BigDecimal.valueOf(18.1), BigDecimal.valueOf(18.2),
            BigDecimal.valueOf(18.3), BigDecimal.valueOf(18.1), BigDecimal.valueOf(18.2),
            BigDecimal.valueOf(18.2), BigDecimal.valueOf(18.0), BigDecimal.valueOf(17.9),
            BigDecimal.valueOf(18.1), BigDecimal.valueOf(18.2), BigDecimal.valueOf(18.3),
            BigDecimal.valueOf(18.1), BigDecimal.valueOf(18.2), BigDecimal.valueOf(18.2)
        };
        BigDecimal[] doublePrevention = new BigDecimal[currentHour + 1];
        System.arraycopy(doublePreventionData, 0, doublePrevention, 0, currentHour + 1);
        result.put("doublePrevention", doublePrevention);

        // 控制回路
        BigDecimal[] controlCircuitData = {
            BigDecimal.valueOf(4.9), BigDecimal.valueOf(4.8), BigDecimal.valueOf(4.7),
            BigDecimal.valueOf(4.2), BigDecimal.valueOf(3.6), BigDecimal.valueOf(0),
            BigDecimal.valueOf(0), BigDecimal.valueOf(0), BigDecimal.valueOf(4.9),
            BigDecimal.valueOf(4.8), BigDecimal.valueOf(4.7), BigDecimal.valueOf(4.2),
            BigDecimal.valueOf(3.6), BigDecimal.valueOf(0), BigDecimal.valueOf(0),
            BigDecimal.valueOf(0), BigDecimal.valueOf(4.9), BigDecimal.valueOf(4.8),
            BigDecimal.valueOf(4.7), BigDecimal.valueOf(4.2), BigDecimal.valueOf(3.6),
            BigDecimal.valueOf(0), BigDecimal.valueOf(0), BigDecimal.valueOf(0)
        };
        BigDecimal[] controlCircuit = new BigDecimal[currentHour + 1];
        System.arraycopy(controlCircuitData, 0, controlCircuit, 0, currentHour + 1);
        result.put("controlCircuit", controlCircuit);

        // 设备可靠性
        BigDecimal[] deviceRunData = {
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.3), BigDecimal.valueOf(14.0),
            BigDecimal.valueOf(14.4), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.2),
            BigDecimal.valueOf(14.3), BigDecimal.valueOf(14.4), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.3), BigDecimal.valueOf(14.0), BigDecimal.valueOf(14.4),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.2), BigDecimal.valueOf(14.3),
            BigDecimal.valueOf(14.4), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.3),
            BigDecimal.valueOf(14.0), BigDecimal.valueOf(14.4), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.2), BigDecimal.valueOf(14.3), BigDecimal.valueOf(14.4)
        };
        BigDecimal[] deviceRun = new BigDecimal[currentHour + 1];
        System.arraycopy(deviceRunData, 0, deviceRun, 0, currentHour + 1);
        result.put("deviceRun", deviceRun);

        // 工艺报警
        BigDecimal[] processAlarmData = {
            BigDecimal.valueOf(14.6), BigDecimal.valueOf(14.5), BigDecimal.valueOf(14.0),
            BigDecimal.valueOf(14.7), BigDecimal.valueOf(14.5), BigDecimal.valueOf(14.6),
            BigDecimal.valueOf(14.5), BigDecimal.valueOf(14.7), BigDecimal.valueOf(14.6),
            BigDecimal.valueOf(14.5), BigDecimal.valueOf(14.0), BigDecimal.valueOf(14.7),
            BigDecimal.valueOf(14.5), BigDecimal.valueOf(14.6), BigDecimal.valueOf(14.5),
            BigDecimal.valueOf(14.7), BigDecimal.valueOf(14.6), BigDecimal.valueOf(14.5),
            BigDecimal.valueOf(14.0), BigDecimal.valueOf(14.7), BigDecimal.valueOf(14.5),
            BigDecimal.valueOf(14.6), BigDecimal.valueOf(14.5), BigDecimal.valueOf(14.7)
        };
        BigDecimal[] processAlarm = new BigDecimal[currentHour + 1];
        System.arraycopy(processAlarmData, 0, processAlarm, 0, currentHour + 1);
        result.put("processAlarm", processAlarm);

        // SIS连锁
        BigDecimal[] sisSideData = {
            BigDecimal.valueOf(12.6), BigDecimal.valueOf(12.5), BigDecimal.valueOf(12.0),
            BigDecimal.valueOf(12.7), BigDecimal.valueOf(12.5), BigDecimal.valueOf(12.6),
            BigDecimal.valueOf(12.5), BigDecimal.valueOf(12.75), BigDecimal.valueOf(12.6),
            BigDecimal.valueOf(12.5), BigDecimal.valueOf(12.0), BigDecimal.valueOf(12.7),
            BigDecimal.valueOf(12.5), BigDecimal.valueOf(12.6), BigDecimal.valueOf(12.5),
            BigDecimal.valueOf(12.75), BigDecimal.valueOf(12.6), BigDecimal.valueOf(12.5),
            BigDecimal.valueOf(12.0), BigDecimal.valueOf(12.7), BigDecimal.valueOf(12.5),
            BigDecimal.valueOf(12.6), BigDecimal.valueOf(12.5), BigDecimal.valueOf(12.75)
        };
        BigDecimal[] sisSide = new BigDecimal[currentHour + 1];
        System.arraycopy(sisSideData, 0, sisSide, 0, currentHour + 1);
        result.put("sisSide", sisSide);

        // GDS报警
        BigDecimal[] gdsAlarmData = {
            BigDecimal.valueOf(4.9), BigDecimal.valueOf(4.8), BigDecimal.valueOf(4.75),
            BigDecimal.valueOf(4.7), BigDecimal.valueOf(4.5), BigDecimal.valueOf(4.95),
            BigDecimal.valueOf(4.9), BigDecimal.valueOf(4.25), BigDecimal.valueOf(4.9),
            BigDecimal.valueOf(4.8), BigDecimal.valueOf(4.75), BigDecimal.valueOf(4.7),
            BigDecimal.valueOf(4.5), BigDecimal.valueOf(4.95), BigDecimal.valueOf(4.9),
            BigDecimal.valueOf(4.25), BigDecimal.valueOf(4.9), BigDecimal.valueOf(4.8),
            BigDecimal.valueOf(4.75), BigDecimal.valueOf(4.7), BigDecimal.valueOf(4.5),
            BigDecimal.valueOf(4.95), BigDecimal.valueOf(4.9), BigDecimal.valueOf(4.25)
        };
        BigDecimal[] gdsAlarm = new BigDecimal[currentHour + 1];
        System.arraycopy(gdsAlarmData, 0, gdsAlarm, 0, currentHour + 1);
        result.put("gdsAlarm", gdsAlarm);

        // 特殊作业
        BigDecimal[] specialWorkData = {
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1),
            BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1), BigDecimal.valueOf(14.1)
        };
        BigDecimal[] specialWork = new BigDecimal[currentHour + 1];
        System.arraycopy(specialWorkData, 0, specialWork, 0, currentHour + 1);
        result.put("specialWork", specialWork);

        // 人员聚集
        BigDecimal[] personAggregationData = {
            BigDecimal.valueOf(10), BigDecimal.valueOf(10), BigDecimal.valueOf(10),
            BigDecimal.valueOf(10), BigDecimal.valueOf(10), BigDecimal.valueOf(10),
            BigDecimal.valueOf(10), BigDecimal.valueOf(9.5), BigDecimal.valueOf(10),
            BigDecimal.valueOf(10), BigDecimal.valueOf(10), BigDecimal.valueOf(10),
            BigDecimal.valueOf(10), BigDecimal.valueOf(10), BigDecimal.valueOf(10),
            BigDecimal.valueOf(9.5), BigDecimal.valueOf(10), BigDecimal.valueOf(10),
            BigDecimal.valueOf(10), BigDecimal.valueOf(10), BigDecimal.valueOf(10),
            BigDecimal.valueOf(10), BigDecimal.valueOf(10), BigDecimal.valueOf(9.5)
        };
        BigDecimal[] personAggregation = new BigDecimal[currentHour + 1];
        System.arraycopy(personAggregationData, 0, personAggregation, 0, currentHour + 1);
        result.put("personAggregation", personAggregation);
        return R.ok(result);
    }

    /**
     * 创建风险子项
     */
    private RiskSubItemVo createSubItem(String subTypeName, Byte isNegated, BigDecimal deductionScore, String deductionReason) {
        RiskSubItemVo subItem = new RiskSubItemVo();
        subItem.setSubTypeName(subTypeName);
        subItem.setIsNegated(isNegated);
        subItem.setDeductionScore(deductionScore);
        subItem.setDeductionReason(deductionReason);
        return subItem;
    }
}
